import { mergeWith } from 'lodash';

const initialState = {
  articleList: {} as {
    [key: number]: { results: ArticleType[]; pre_timestamp: number };
  },

  // 1. 设置state和初始值，并且设置初始值类型
  detail: {} as ArticleDetail,
};

type ActionType =
  | {
      type: 'article/saveList';
      payload: {
        channel_id: number;
        pre_timestamp: number;
        results: ArticleType[];
      };
    }
  | {
      type: 'article/updateListById';
      payload: {
        channel_id: number;
        pre_timestamp: number;
        results: ArticleType[];
      };
    }
  // 2. 扩展actionType的类型
  | { type: 'article/saveDetail'; payload: ArticleDetail };

export default function articleReducer(
  state = initialState,
  action: ActionType
): typeof initialState {
  switch (action.type) {
    case 'article/saveList':
      return {
        ...state,
        articleList: {
          ...state.articleList,
          [action.payload.channel_id]: {
            pre_timestamp: action.payload.pre_timestamp,
            results: action.payload.results,
          },
        },
      };

    case 'article/updateListById':
      const oldArticleData = state.articleList[action.payload.channel_id];
      const updateArticleData = {
        results: action.payload.results,
        pre_timestamp: action.payload.pre_timestamp,
      };

      const newData = mergeWith(
        oldArticleData,
        updateArticleData,
        (oldValue, newValue) => {
          if (Array.isArray(newValue)) {
            return [...oldValue, ...newValue];
          }
          return newValue;
        }
      );
      return {
        ...state,
        articleList: {
          ...state.articleList,
          [action.payload.channel_id]: newData,
        },
      };
    // 3. 编写switch逻辑分支
    case 'article/saveDetail':
      return {
        ...state,
        detail: { ...action.payload },
      };

    default:
      return state;
  }
}

export type ArticleType = {
  art_id: string;
  title: string;
  aut_id: string;
  comm_count: number;
  pubdate: string;
  aut_name: string;
  is_top: number;
  cover: {
    type: number;
    images: string[];
  };
};
export type ArticleDetail = {
  art_id: string;
  title: string;
  pubdate: string;
  aut_id: string;
  content: string;
  aut_name: string;
  aut_photo: string;
  is_followed: boolean;
  is_collected: boolean;
  attitude: number;
  comm_count: number;
  read_count: number;
  like_count: number;
};
